package com.woniu.jifen.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.dto.UserDto;
import com.woniu.common.util.GetUserInfoUtil;
import com.woniu.common.util.PageParam;
import com.woniu.common.util.ResponseData;
import com.woniu.common.util.ResponseEnum;
import com.woniu.jifen.entity.ACoupon;
import com.woniu.jifen.entity.AUserCoupon;
import com.woniu.jifen.entity.TUser;
import com.woniu.jifen.service.ACouponService;
import com.woniu.jifen.mapper.ACouponMapper;
import com.woniu.jifen.service.AUserCouponService;
import com.woniu.jifen.service.TUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
* @author s‘’w
* @description 针对表【a_coupon(优惠券)】的数据库操作Service实现
* @createDate 2024-05-21 19:29:03
*/
@Service
public class ACouponServiceImpl extends ServiceImpl<ACouponMapper, ACoupon>
    implements ACouponService{

    private static final List<Integer> PRIZE_IDS = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
    private static final Random RANDOM = new Random();


    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public ResponseData<?> queryCouponBySortId(PageParam<ACoupon> pageParam) {
        // 创建Page对象，第一个参数是当前页，第二个参数是每页的数量
        Page<ACoupon> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());

        // 使用Page对象进行分页查询
        IPage<ACoupon> iPage = lambdaQuery().eq(ACoupon::getSortId, pageParam.getParam().getSortId())
                .eq(ACoupon::getAvailable,1).page(page);

        long total = iPage.getTotal();

        return new ResponseData<>().ok(iPage, String.valueOf(total));
    }

    @Autowired
    private TUserService userService;
    @Autowired
    private AUserCouponService userCouponService;
    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public ResponseData<?> buyCouponById(Integer id){

        redisTemplate.delete("userCoupon");

        ACoupon coupon = lambdaQuery().eq(ACoupon::getId, id).one();
        if(coupon.getTotal()<=0){
            return new ResponseData<>().fail(ResponseEnum.TOTAL_ERROR);
        }
        //获取用户信息
        UserDto userInfo = GetUserInfoUtil.getUserInfo();


        AUserCoupon one = userCouponService.lambdaQuery().eq(AUserCoupon::getUserId, userInfo.getId())
                .eq(AUserCoupon::getStatus, 0)
                .eq(AUserCoupon::getUserCouponId,id).one();
        if (one!=null){
            return new ResponseData<>().fail(ResponseEnum.HAVING_COUPON);
        }

        AUserCoupon userCoupon = new AUserCoupon();
        userCoupon.setUserCouponId(coupon.getId());
        userCoupon.setUserId(userInfo.getId());
        userCoupon.setCreateTime(DateUtil.now());
        userCoupon.setStatus(0);
        userCoupon.setSortId(coupon.getSortId());
        userCoupon.setName(coupon.getName());
        //扣除用户积分
        userService.lambdaUpdate().setSql("integral = integral -" + coupon.getIntegral())
                .eq(TUser::getId,userInfo.getId()).update();
        //消减库存
        lambdaUpdate().setSql("total = total -" + 1)
                .eq(ACoupon::getId,id).update();
        //保存用户优惠券
        userCouponService.save(userCoupon);
        return new ResponseData<>().ok();
    }

    /**
     * 查出用于积分抽奖的奖品
     * @param phone
     * @return
     */
    @Override
    public List<ACoupon> queryAll(String phone) {

        // 先尝试从Redis中获取数据
        String json = redisTemplate.opsForValue().get(phone);
        if (json != null && !json.isEmpty()) {
            // 如果找到，直接返回
            return JSON.parseArray(json, ACoupon.class);
        }

        List<ACoupon> list = lambdaQuery().eq(ACoupon::getAvailable, 1).list();
        Collections.shuffle(list);
        List<ACoupon> aCoupons = list.subList(0, Math.min(7, list.size()));

        // 创建一个新的ACoupon对象，设置它的属性为"谢谢惠顾"
        ACoupon thanksCoupon = new ACoupon();
        thanksCoupon.setName("谢谢惠顾");
        // 添加到列表的末尾
        aCoupons.add(thanksCoupon);

        // 存储到Redis
        json = JSON.toJSONString(aCoupons);
        redisTemplate.opsForValue().set(phone, json, 5, TimeUnit.DAYS);


        return aCoupons;
    }

    /**
     * 得到奖品id
     * @return
     */
    @Override
    public ResponseData<?> getPrizeId(String phone) {

        //从redis中获得该用户的抽奖品
        String json = redisTemplate.opsForValue().get(phone);
        List<ACoupon> aCoupons = JSON.parseArray(json, ACoupon.class);

        int highestIntegral = -1;//最高商品的积分
        int highestIntegralIndex = -1;//最高商品的位置
        for (int i = 0; i < aCoupons.size()-1; i++) {
            Integer integral = aCoupons.get(i).getIntegral();
            if (integral > highestIntegral) {
                highestIntegral = integral;
                highestIntegralIndex = i;
            }
        }
        System.out.println(highestIntegralIndex);

        // 生成一个0-99的随机数
        int randomNum = RANDOM.nextInt(100);

        int prizeId;
        if (randomNum < 90) { // 90%的概率返回5
            prizeId = 5;
        } else { // 80%的概率从PRIZE_IDS中随机选择
            List<Integer> PRIZE_IDS = Arrays.asList(1, 2, 3, 4, 6, 7, 8, 9, 10);
            prizeId = PRIZE_IDS.get(RANDOM.nextInt(PRIZE_IDS.size()));
        }

//        // 从 PRIZE_IDS 列表中随机选择一个抽奖 ID
//        int prizeId = PRIZE_IDS.get(RANDOM.nextInt(PRIZE_IDS.size()));


        return new ResponseData<>().ok(prizeId);

    }

    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public ResponseData<?> buyCoupon1(Integer id,String phone) {
        redisTemplate.delete("userCoupon");

        ACoupon coupon = lambdaQuery().eq(ACoupon::getId, id).one();
        if(coupon.getTotal()<=0){
            return new ResponseData<>().fail(ResponseEnum.TOTAL_ERROR);
        }
        TUser user = userService.lambdaQuery().eq(TUser::getPhone, phone).one();

        AUserCoupon userCoupon = new AUserCoupon();
        userCoupon.setUserCouponId(coupon.getId());
        userCoupon.setUserId(user.getId());
        userCoupon.setCreateTime(DateUtil.now());
        userCoupon.setStatus(0);
        userCoupon.setSortId(coupon.getSortId());
        userCoupon.setName(coupon.getName());
        //扣除用户积分
        userService.lambdaUpdate().setSql("integral = integral -" + 150)
                .eq(TUser::getId,user.getId()).update();
        //消减库存
        lambdaUpdate().setSql("total = total -" + 1)
                .eq(ACoupon::getId,id).update();
        //保存用户优惠券
        userCouponService.save(userCoupon);

        return null;
    }

    @Override
    public List<ACoupon> queryAllCoupons() {

        return lambdaQuery().eq(ACoupon::getAvailable, 1).list();
    }
}




